Data 608 Module 2¶

  • Gabriel Santos
  • 2/24/2023
In [1]:
import numpy as np
import pandas as pd
import urllib
import json
import datetime

import plotly.offline as py
import plotly.graph_objs as go
from plotly import tools

# from shapely.geometry import Point, Polygon, shape
# In order to get shapley, you'll need to run [pip install shapely.geometry] from your terminal

from functools import partial

from IPython.display import GeoJSON

py.init_notebook_mode()

For module 2 we'll be looking at techniques for dealing with big data. In particular binning strategies and the datashader library (which possibly proves we'll never need to bin large data for visualization ever again.)

To demonstrate these concepts we'll be looking at the PLUTO dataset put out by New York City's department of city planning. PLUTO contains data about every tax lot in New York City.

For the analysis I chose the dataset: https://www.nyc.gov/assets/planning/download/zip/data-maps/open-data/plutochangefile20v1.zip

In [3]:
import requests, zipfile
from io import BytesIO
print('Downloading started')

#Defining the zip file URL
url = 'https://www.nyc.gov/assets/planning/download/zip/data-maps/open-data/nyc_pluto_20v1_csv.zip'
filename = url.split('/')[-1]

# Downloading the file by sending the request to the URL
req = requests.get(url)
print('Downloading Completed')

# extracting the zip file contents
zipfile= zipfile.ZipFile(BytesIO(req.content))
zipfile.extractall('E:/Users/drake/Documents/CUNY SPS/MASTERS/DATA 608/Week 5/Datafolder')
Downloading started
Downloading Completed
In [5]:
# Code to read in v17, column names have been updated (without upper case letters) for v18

# bk = pd.read_csv('PLUTO17v1.1/BK2017V11.csv')
# bx = pd.read_csv('PLUTO17v1.1/BX2017V11.csv')
# mn = pd.read_csv('PLUTO17v1.1/MN2017V11.csv')
# qn = pd.read_csv('PLUTO17v1.1/QN2017V11.csv')
# si = pd.read_csv('PLUTO17v1.1/SI2017V11.csv')

# ny = pd.concat([bk, bx, mn, qn, si], ignore_index=True)
ny = pd.read_csv('E:\\Users\\drake\\Documents\\CUNY SPS\\MASTERS\\DATA 608\\Week 5\\Datafolder\\pluto_20v1.csv')

# Getting rid of some outliers
ny = ny[(ny['yearbuilt'] > 1850) & (ny['yearbuilt'] < 2020) & (ny['numfloors'] != 0)]
ny.head()
C:\Users\drake\AppData\Local\Temp\ipykernel_20112\2124455104.py:10: DtypeWarning:

Columns (17,18,20,22) have mixed types. Specify dtype option on import or set low_memory=False.

Out[5]:
borough block lot cd ct2010 cb2010 schooldist council zipcode firecomp ... dcasdate zoningdate landmkdate basempdate masdate polidate edesigdate geom dcpedited notes
0 BK 834 46 307.0 106.0 2001.0 20.0 38.0 11220.0 L114 ... NaN NaN NaN NaN NaN NaN NaN 0106000020E61000000100000001030000000100000005... NaN NaN
1 QN 4042 106 407.0 929.0 3000.0 25.0 19.0 11356.0 E297 ... NaN NaN NaN NaN NaN NaN NaN 0106000020E61000000100000001030000000100000007... NaN NaN
2 BK 4679 17 317.0 866.0 3002.0 18.0 41.0 11203.0 L174 ... NaN NaN NaN NaN NaN NaN NaN 0106000020E61000000100000001030000000100000006... NaN NaN
3 BK 7831 6 318.0 676.0 1002.0 22.0 46.0 11234.0 L159 ... NaN NaN NaN NaN NaN NaN NaN 0106000020E61000000100000001030000000100000005... NaN NaN
4 BK 7831 7 318.0 676.0 1002.0 22.0 46.0 11234.0 L159 ... NaN NaN NaN NaN NaN NaN NaN 0106000020E61000000100000001030000000100000005... NaN NaN

5 rows × 99 columns

I'll also do some prep for the geographic component of this data, which we'll be relying on for datashader.

You're not required to know how I'm retrieving the lattitude and longitude here, but for those interested: this dataset uses a flat x-y projection (assuming for a small enough area that the world is flat for easier calculations), and this needs to be projected back to traditional lattitude and longitude.

In [ ]:
# wgs84 = Proj("+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs")
# nyli = Proj("+proj=lcc +lat_1=40.66666666666666 +lat_2=41.03333333333333 +lat_0=40.16666666666666 +lon_0=-74 +x_0=300000 +y_0=0 +ellps=GRS80 +datum=NAD83 +to_meter=0.3048006096012192 +no_defs")
# ny['xcoord'] = 0.3048*ny['xcoord']
# ny['ycoord'] = 0.3048*ny['ycoord']
# ny['lon'], ny['lat'] = transform(nyli, wgs84, ny['xcoord'].values, ny['ycoord'].values)

# ny = ny[(ny['lon'] < -60) & (ny['lon'] > -100) & (ny['lat'] < 60) & (ny['lat'] > 20)]

#Defining some helper functions for DataShader
background = "black"
export = partial(export_image, background = background, export_path="export")
cm = partial(colormap_select, reverse=(background!="black"))

Part 1: Binning and Aggregation¶

Binning is a common strategy for visualizing large datasets. Binning is inherent to a few types of visualizations, such as histograms and 2D histograms (also check out their close relatives: 2D density plots and the more general form: heatmaps.

While these visualization types explicitly include binning, any type of visualization used with aggregated data can be looked at in the same way. For example, lets say we wanted to look at building construction over time. This would be best viewed as a line graph, but we can still think of our results as being binned by year:

In [6]:
trace = go.Scatter(
    # I'm choosing BBL here because I know it's a unique key.
    x = ny.groupby('yearbuilt').count()['bbl'].index,
    y = ny.groupby('yearbuilt').count()['bbl']
)

layout = go.Layout(
    xaxis = dict(title = 'Year Built'),
    yaxis = dict(title = 'Number of Lots Built')
)

fig = go.FigureWidget(data = [trace], layout = layout)

fig
FigureWidget({
    'data': [{'type': 'scatter',
              'uid': '23ec0f51-02ba-4fb7-b370-d57092bd5284',
 …

Something looks off... You're going to have to deal with this imperfect data to answer this first question.

But first: some notes on pandas. Pandas dataframes are a different beast than R dataframes, here are some tips to help you get up to speed:


Hello all, here are some pandas tips to help you guys through this homework:

Indexing and Selecting: .loc and .iloc are the analogs for base R subsetting, or filter() in dplyr

Group By: This is the pandas analog to group_by() and the appended function the analog to summarize(). Try out a few examples of this, and display the results in Jupyter. Take note of what's happening to the indexes, you'll notice that they'll become hierarchical. I personally find this more of a burden than a help, and this sort of hierarchical indexing leads to a fundamentally different experience compared to R dataframes. Once you perform an aggregation, try running the resulting hierarchical datafrome through a reset_index().

Reset_index: I personally find the hierarchical indexes more of a burden than a help, and this sort of hierarchical indexing leads to a fundamentally different experience compared to R dataframes. reset_index() is a way of restoring a dataframe to a flatter index style. Grouping is where you'll notice it the most, but it's also useful when you filter data, and in a few other split-apply-combine workflows. With pandas indexes are more meaningful, so use this if you start getting unexpected results.

Indexes are more important in Pandas than in R. If you delve deeper into the using python for data science, you'll begin to see the benefits in many places (despite the personal gripes I highlighted above.) One place these indexes come in handy is with time series data. The pandas docs have a huge section on datetime indexing. In particular, check out resample, which provides time series specific aggregation.

Merging, joining, and concatenation: There's some overlap between these different types of merges, so use this as your guide. Concat is a single function that replaces cbind and rbind in R, and the results are driven by the indexes. Read through these examples to get a feel on how these are performed, but you will have to manage your indexes when you're using these functions. Merges are fairly similar to merges in R, similarly mapping to SQL joins.

Apply: This is explained in the "group by" section linked above. These are your analogs to the plyr library in R. Take note of the lambda syntax used here, these are anonymous functions in python. Rather than predefining a custom function, you can just define it inline using lambda.

Browse through the other sections for some other specifics, in particular reshaping and categorical data (pandas' answer to factors.) Pandas can take a while to get used to, but it is a pretty strong framework that makes more advanced functions easier once you get used to it. Rolling functions for example follow logically from the apply workflow (and led to the best google results ever when I first tried to find this out and googled "pandas rolling")

Google Wes Mckinney's book "Python for Data Analysis," which is a cookbook style intro to pandas. It's an O'Reilly book that should be pretty available out there.


Question¶

After a few building collapses, the City of New York is going to begin investigating older buildings for safety. The city is particularly worried about buildings that were unusually tall when they were built, since best-practices for safety hadn’t yet been determined. Create a graph that shows how many buildings of a certain number of floors were built in each year (note: you may want to use a log scale for the number of buildings). Find a strategy to bin buildings (It should be clear 20-29-story buildings, 30-39-story buildings, and 40-49-story buildings were first built in large numbers, but does it make sense to continue in this way as you get taller?)

For the analysis filter by 'year built' and 'num floors'. Then make the graph.

In [7]:
yr_flr_ny = ny[['yearbuilt', 'numfloors']]

yr_flr_ny['y1'] = (yr_flr_ny['yearbuilt'] // 1 * 1).astype(int) 
bins = (0, 1, 2, 5, 10, 20, 30, 40, 50, 60, 80, 100, 210)

count_df = yr_flr_ny.groupby(['y1', pd.cut(yr_flr_ny['numfloors'], bins)]).count().drop(['numfloors'], axis=1) \
       .fillna(0).reset_index()

yr_flr_ny.head()
C:\Users\drake\AppData\Local\Temp\ipykernel_20112\2720250741.py:3: SettingWithCopyWarning:


A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

Out[7]:
yearbuilt numfloors y1
0 1931.0 3.00 1931
1 1910.0 2.75 1910
2 1920.0 2.00 1920
3 1920.0 2.00 1920
4 1920.0 2.00 1920

Graph 1¶

In [8]:
import plotly.graph_objects as go
groups = count_df.groupby('numfloors')
fig = go.Figure()
for g in groups.groups:
    group = groups.get_group(g)
    fig.add_trace(go.Bar(x=group['y1'], y=group['yearbuilt'], name=str(g)))
fig.update_layout(barmode='stack', xaxis={'categoryorder':'category ascending'}, \
                  title_text = "Quantity of Buildings according to Number of Floors in each Year")
fig.update_xaxes(title_text="Years")
fig.update_yaxes(title_text="Buildings Count")
fig.show()

For a better visualization I group the years by decades. Later I make the graph.

In [9]:
yr_flr_ny = ny[['yearbuilt', 'numfloors']]

yr_flr_ny['y10'] = (yr_flr_ny['yearbuilt'] // 10 * 10).astype(int) 
bins = (0, 1, 2, 5, 10, 20, 30, 40, 50, 60, 80, 100, 210)

count_df = yr_flr_ny.groupby(['y10', pd.cut(yr_flr_ny['numfloors'], bins)]).count().drop(['numfloors'], axis=1) \
       .fillna(0).reset_index()

yr_flr_ny.head()
C:\Users\drake\AppData\Local\Temp\ipykernel_20112\48753875.py:3: SettingWithCopyWarning:


A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

Out[9]:
yearbuilt numfloors y10
0 1931.0 3.00 1930
1 1910.0 2.75 1910
2 1920.0 2.00 1920
3 1920.0 2.00 1920
4 1920.0 2.00 1920

Graph 2¶

In [10]:
import plotly.graph_objects as go
groups = count_df.groupby('numfloors')
fig = go.Figure()
for g in groups.groups:
    group = groups.get_group(g)
    fig.add_trace(go.Bar(x=group['y10'], y=group['yearbuilt'], name=str(g)))
fig.update_layout(barmode='stack', xaxis={'categoryorder':'category ascending'}, \
                  title_text = "Quantity of Buildings according to Number of Floors in each Decade")
fig.update_xaxes(title_text="Years")
fig.update_yaxes(title_text="Buildings Count")
fig.show()

According to the initial graphs we can see that most of the buildings built are from 1 to 5 floors. It is not easily identifiable the buildings of the 20-29-story buildings, the 30-39-story buildings, and the 40-49-story buildings were first built in large numbers. So he decided to use a logarithmic base 10 to the counts. Then graph.

In [11]:
bins = [0, 19, 29, 39, 49, 100]
floor_labels = ['1-19','20-29','30-39','40-49','50-100']

ny['floor_bins'] = pd.cut(ny['numfloors'], bins=bins, labels=floor_labels)
print (ny.groupby(['floor_bins']).size())
floor_bins
1-19      809749
20-29       1099
30-39        473
40-49        223
50-100       136
dtype: int64
In [12]:
decade_labels = pd.Series(np.arange(1850,2020,10))
ny['decade'] = pd.cut(ny['yearbuilt'], bins=pd.Series(np.arange(1849,2029,10)), labels=decade_labels)
ny[['yearbuilt','decade','floor_bins']].head()
ny_group = ny.groupby(['decade', 'floor_bins']).size().reset_index(name='count')
ny_group.head()
Out[12]:
decade floor_bins count
0 1850 1-19 1555
1 1850 20-29 0
2 1850 30-39 0
3 1850 40-49 0
4 1850 50-100 0
In [13]:
ny_group.drop(ny_group.loc[ny_group['count']==0].index, inplace=True)

ny_group['count_base10'] = np.log10(ny_group['count'])

# Ordered the floor_bins column to ensure the final chart displays the floor bins in numerical order.
ny_group.sort_values('floor_bins', inplace=True)

ny_group.head()
Out[13]:
decade floor_bins count count_base10
0 1850 1-19 1555 3.191730
80 2010 1-19 14812 4.170614
75 2000 1-19 42871 4.632164
70 1990 1-19 28872 4.460477
65 1980 1-19 27025 4.431766

Graph 3¶

In [14]:
import plotly.express as px
fig_ny = px.bar(ny_group, x="decade", y="count_base10", color="floor_bins",
               color_discrete_sequence=px.colors.qualitative.Set1,
               height=700,
               title="Quantity of Buildings according to Number of Floors in each Decade",
               labels={
                  "count_base10": "Log Base 10 of Count",
                  "floor_bins": "Floors"
               })
fig_ny.update_layout(legend_traceorder="reversed")
fig_ny.show()

Part 2: Datashader¶

Datashader is a library from Anaconda that does away with the need for binning data. It takes in all of your datapoints, and based on the canvas and range returns a pixel-by-pixel calculations to come up with the best representation of the data. In short, this completely eliminates the need for binning your data.

As an example, lets continue with our question above and look at a 2D histogram of YearBuilt vs NumFloors:

Graph 4¶

In [15]:
yearbins = 200
floorbins = 200

yearBuiltCut = pd.cut(ny['yearbuilt'], np.linspace(ny['yearbuilt'].min(), ny['yearbuilt'].max(), yearbins))
numFloorsCut = pd.cut(ny['numfloors'], np.logspace(1, np.log(ny['numfloors'].max()), floorbins))

xlabels = np.floor(np.linspace(ny['yearbuilt'].min(), ny['yearbuilt'].max(), yearbins))
ylabels = np.floor(np.logspace(1, np.log(ny['numfloors'].max()), floorbins))

fig = go.FigureWidget(
    data = [
        go.Heatmap(z = ny.groupby([numFloorsCut, yearBuiltCut])['bbl'].count().unstack().fillna(0).values,
              colorscale = 'Greens', x = xlabels, y = ylabels)
    ]
)

fig
FigureWidget({
    'data': [{'colorscale': [[0.0, 'rgb(247,252,245)'], [0.125,
                             'r…

This shows us the distribution, but it's subject to some biases discussed in the Anaconda notebook Plotting Perils.

Here is what the same plot would look like in datashader:

In [16]:
import datashader as ds
import datashader.transfer_functions as tf
import datashader.glyphs
from datashader import reductions
from datashader.core import bypixel
from datashader.utils import lnglat_to_meters as webm, export_image
from datashader.colors import colormap_select, Greys9, viridis, inferno
import copy

background = "black"
export = partial(export_image, background = background, export_path="export")
cm = partial(colormap_select, reverse=(background!="black"))
cvs = ds.Canvas(800, 500, x_range = (ny['yearbuilt'].min(), ny['yearbuilt'].max()), 
                                y_range = (ny['numfloors'].min(), ny['numfloors'].max()))
agg = cvs.points(ny, 'yearbuilt', 'numfloors')
view = tf.shade(agg, cmap = cm(Greys9), how='log')
export(tf.spread(view, px=2), 'yearvsnumfloors')
Out[16]:

That's technically just a scatterplot, but the points are smartly placed and colored to mimic what one gets in a heatmap. Based on the pixel size, it will either display individual points, or will color the points of denser regions.

Datashader really shines when looking at geographic information. Here are the latitudes and longitudes of our dataset plotted out, giving us a map of the city colored by density of structures:

In [17]:
NewYorkCity   = (( 913164.0,  1067279.0), (120966.0, 272275.0))
cvs = ds.Canvas(700, 700, *NewYorkCity)
agg = cvs.points(ny, 'xcoord', 'ycoord')
view = tf.shade(agg, cmap = cm(inferno), how='log')
export(tf.spread(view, px=2), 'firery')
Out[17]:

Interestingly, since we're looking at structures, the large buildings of Manhattan show up as less dense on the map. The densest areas measured by number of lots would be single or multi family townhomes.

Unfortunately, Datashader doesn't have the best documentation. Browse through the examples from their github repo. I would focus on the visualization pipeline and the US Census Example for the question below. Feel free to use my samples as templates as well when you work on this problem.

Question¶

You work for a real estate developer and are researching underbuilt areas of the city. After looking in the Pluto data dictionary, you've discovered that all tax assessments consist of two parts: The assessment of the land and assessment of the structure. You reason that there should be a correlation between these two values: more valuable land will have more valuable structures on them (more valuable in this case refers not just to a mansion vs a bungalow, but an apartment tower vs a single family home). Deviations from the norm could represent underbuilt or overbuilt areas of the city. You also recently read a really cool blog post about bivariate choropleth maps, and think the technique could be used for this problem.

Datashader is really cool, but it's not that great at labeling your visualization. Don't worry about providing a legend, but provide a quick explanation as to which areas of the city are overbuilt, which areas are underbuilt, and which areas are built in a way that's properly correlated with their land value.

In [18]:
from matplotlib import cm as mcm 
cvs = ds.Canvas(700, 700, *NewYorkCity)
agg = cvs.points(ny, 'xcoord', 'ycoord', ds.sum('assessland'))
image = tf.shade(agg, cmap = mcm.Blues, how='eq_hist', alpha=100)

export(image, 'Assessment Land Value')
Out[18]:

This map allows us to identify which areas are overvalued. The most overrated areas are the darkest areas. We identify which are the lands with the highest value.

In [19]:
cvs = ds.Canvas(700, 700, *NewYorkCity)
agg = cvs.points(ny, 'xcoord', 'ycoord', ds.sum('assesstot'))
image1 = tf.shade(agg, cmap = mcm.Oranges, how='eq_hist', alpha=100)

export(image1, 'Assessment Total Value')
Out[19]:

This map allows us to identify which areas have the structures with the highest value. The darker areas are the areas with a higher total value.

Now, let's calculate the real value of the buildings:

In [20]:
ny['assessbldg'] = ny['assesstot'] - ny['assessland']
ny.head()
Out[20]:
borough block lot cd ct2010 cb2010 schooldist council zipcode firecomp ... basempdate masdate polidate edesigdate geom dcpedited notes floor_bins decade assessbldg
0 BK 834 46 307.0 106.0 2001.0 20.0 38.0 11220.0 L114 ... NaN NaN NaN NaN 0106000020E61000000100000001030000000100000005... NaN NaN 1-19 1930 204300.0
1 QN 4042 106 407.0 929.0 3000.0 25.0 19.0 11356.0 E297 ... NaN NaN NaN NaN 0106000020E61000000100000001030000000100000007... NaN NaN 1-19 1910 66660.0
2 BK 4679 17 317.0 866.0 3002.0 18.0 41.0 11203.0 L174 ... NaN NaN NaN NaN 0106000020E61000000100000001030000000100000006... NaN NaN 1-19 1920 16260.0
3 BK 7831 6 318.0 676.0 1002.0 22.0 46.0 11234.0 L159 ... NaN NaN NaN NaN 0106000020E61000000100000001030000000100000005... NaN NaN 1-19 1920 16920.0
4 BK 7831 7 318.0 676.0 1002.0 22.0 46.0 11234.0 L159 ... NaN NaN NaN NaN 0106000020E61000000100000001030000000100000005... NaN NaN 1-19 1920 21600.0

5 rows × 102 columns

Organize the data to identify areas with suitable land and building value.

In [21]:
labels_land = ['A', 'B', 'C'] 
labels_bldg = ['1', '2', '3'] 

pct = 100 / 3

bp_land = np.percentile(ny['assessland'], [pct, 100 - pct], axis=0)
bp_bldg = np.percentile(ny['assessbldg'], [pct, 100 - pct], axis=0)

ny['land_label'] = pd.cut(ny['assessland'], [0, bp_land[0], bp_land[1], np.inf], right=False, labels=labels_land)

ny['bldg_label'] = pd.cut(ny['assessbldg'], [0, bp_bldg[0], bp_bldg[1], np.inf], right=False, labels=labels_bldg)
ny['color'] = ny['land_label'].astype(str) + ny['bldg_label'].astype(str)
ny['color'] = pd.Categorical(ny['color'])
ny.head()
Out[21]:
borough block lot cd ct2010 cb2010 schooldist council zipcode firecomp ... edesigdate geom dcpedited notes floor_bins decade assessbldg land_label bldg_label color
0 BK 834 46 307.0 106.0 2001.0 20.0 38.0 11220.0 L114 ... NaN 0106000020E61000000100000001030000000100000005... NaN NaN 1-19 1930 204300.0 C 3 C3
1 QN 4042 106 407.0 929.0 3000.0 25.0 19.0 11356.0 E297 ... NaN 0106000020E61000000100000001030000000100000007... NaN NaN 1-19 1910 66660.0 B 3 B3
2 BK 4679 17 317.0 866.0 3002.0 18.0 41.0 11203.0 L174 ... NaN 0106000020E61000000100000001030000000100000006... NaN NaN 1-19 1920 16260.0 C 1 C1
3 BK 7831 6 318.0 676.0 1002.0 22.0 46.0 11234.0 L159 ... NaN 0106000020E61000000100000001030000000100000005... NaN NaN 1-19 1920 16920.0 A 1 A1
4 BK 7831 7 318.0 676.0 1002.0 22.0 46.0 11234.0 L159 ... NaN 0106000020E61000000100000001030000000100000005... NaN NaN 1-19 1920 21600.0 A 1 A1

5 rows × 105 columns

In [22]:
color_key = {'A1':'#64acbe', 'B1':'#627f8c', 'C1':'#574249',   
             'A2':'#b0d5df', 'B2':'#ad9ea5', 'C2':'#985356', 
             'A3':'#e8e8e8', 'B3':'#e4acac', 'C3':'#c85a5a'}
In [23]:
Analysis_NY = (( 913164.0,  1067279.0), (120966.0, 272275.0))
cvs = ds.Canvas(700, 700, *NewYorkCity)
agg = cvs.points(ny, 'xcoord', 'ycoord', ds.count_cat('color'))
imgChoro = tf.shade(agg, color_key=color_key)
export(imgChoro, 'Analysis Final')
Out[23]:

According to the map, we can see that the most overbuilt area is Manhattan. Some areas of Brooklyn and Queens, also have overbuilt areas. The least built-up areas are the areas that have the lightest blue color. The areas are built in a way that correlates well with land values in Manhattan and downtown Brooklyn where the darkest color is found.